from channels.generic.websocket import WebsocketConsumer
from channels.exceptions import StopConsumer
import json

class BuyingInformation(WebsocketConsumer):
    users = []
    def websocket_connect(self, message):
        print("有人来连接")
        self.accept()
        self.users.append(self)

    def websocket_receive(self, message):
        text = message['text']
        print("接收到用户的消息", text)
        for user in self.users:
            user.send(text)

    def websocket_disconnect(self, message):
        print("断开连接")
        self.users.remove(self)
        raise StopConsumer()





"""
from channels.generic.websocket import WebsocketConsumer
from channels.exceptions import StopConsumer
import json
from channels.layers import get_channel_layer
from asgiref.sync import async_to_sync

class BuyingInformation(WebsocketConsumer):
    def connect(self):
        print("有人来连接le")
        self.accept()

    def receive(self, text_data):
        text_data_json = json.loads(text_data)
        message = text_data_json['message']
        print("接收到用户的消息", message)

        # 广播消息给所有连接的客户端
        async_to_sync(self.channel_layer.group_send)(
            'buyinginformation_group',
            {
                'type': 'chat_message',
                'message': message
            }
        )

    def chat_message(self, event):
        # 发送消息给 WebSocket
        message = event['message']

        # Send message to WebSocket
        self.send(text_data=json.dumps({
            'message': message
        }))

    def disconnect(self, close_code):
        print("断开连接")
"""
